package cn.wildfire.chat.app.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lqr.optionitemview.OptionItemView;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import java.io.File;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wildfire.chat.app.Config;
import cn.wildfire.chat.app.extendsion.classes.AndroidVersionUpdateRequest;
import cn.wildfire.chat.app.extendsion.classes.CheckVersionReq;
import cn.wildfire.chat.app.extendsion.ui.CustomAppUIDialog;
import cn.wildfire.chat.app.extendsion.ui.TipDialog;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.utils.SPUtils;
import cn.wildfire.chat.app.extendsion.utils.VariableFilesUtils;
import cn.wildfire.chat.kit.WfcUIKit;
import cn.wildfire.chat.kit.setting.SettingActivity;
import cn.wildfire.chat.kit.user.UserInfoActivity;
import cn.wildfire.chat.kit.user.UserViewModel;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.model.UserInfoExtra;
import cn.wildfirechat.remote.ChatManager;

public class MeFragment extends Fragment {

    @BindView(R2.id.meLinearLayout)
    LinearLayout meLinearLayout;
    @BindView(R2.id.portraitImageView)
    ImageView portraitImageView;
    @BindView(R2.id.nameTextView)
    TextView nameTextView;
    @BindView(R2.id.accountTextView)
    TextView accountTextView;

    @BindView(R2.id.notificationOptionItemView)
    OptionItemView notificationOptionItem;

    @BindView(R2.id.settintOptionItemView)
    TextView settingOptionItem;
    @BindView(R2.id.tv_cache_size)
    TextView tvCacheSize;

    private UserViewModel userViewModel;
    private UserInfo userInfo;

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static int REQUEST_PERMISSION_CODE = 1;

    protected CheckVersionReq checkVersionReq;

    private Observer<List<UserInfo>> userInfoLiveDataObserver = new Observer<List<UserInfo>>() {
        @Override
        public void onChanged(@Nullable List<UserInfo> userInfos) {
            if (userInfos == null) {
                return;
            }
            for (UserInfo info : userInfos) {
                if (info.uid.equals(userViewModel.getUserId())) {
                    userInfo = info;
                    updateUserInfo(userInfo);
                    break;
                }
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_fragment_me, container, false);
        ButterKnife.bind(this, view);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }
        init();
        return view;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private void updateUserInfo(UserInfo userInfo) {
        try {
            Glide.with(this).load(userInfo.portrait).apply(new RequestOptions().placeholder(R.mipmap.avatar_def).centerCrop()).into(portraitImageView);
            nameTextView.setText(userInfo.displayName);
            Gson gson = new Gson();
            UserInfoExtra userInfoExtra = gson.fromJson(userInfo.extra, UserInfoExtra.class);
            if (userInfoExtra != null) {
                String caibaNumber = userInfoExtra.getCaiba_number();
                accountTextView.setText(getString(R.string.caiba_number) + ":" + caibaNumber);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void init() {
        userViewModel = WfcUIKit.getAppScopeViewModel(UserViewModel.class);
        userViewModel.getUserInfoAsync(userViewModel.getUserId(), true)
                .observe(this, info -> {
                    userInfo = info;
                    if (userInfo != null) {
                        updateUserInfo(userInfo);
                    }
                });
        userViewModel.userInfoLiveData().observeForever(userInfoLiveDataObserver);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        userViewModel.userInfoLiveData().removeObserver(userInfoLiveDataObserver);
    }

    @OnClick(R2.id.meLinearLayout)
    void showMyInfo() {
        Intent intent = new Intent(getActivity(), UserInfoActivity.class);
        intent.putExtra("userInfo", userInfo);
        intent.putExtra("fromSelfCenter", "true");
        startActivity(intent);
    }

    @OnClick(R2.id.settintOptionItemView)
    void setting() {
        Intent intent = new Intent(getActivity(), SettingActivity.class);
        startActivity(intent);
    }

    @OnClick(R2.id.notificationOptionItemView)
    void notifyNews() {
        Intent intent = new Intent(getActivity(), NewSettingActivity.class);
        startActivity(intent);
    }

    /**
     * modify by HEKE , 2019/8/15 19:51 TODO  每次页面显示刷新下本用户数据
     */
    public void handleUpdateUserInfo() {
        String[] array = SPUtils.getMuches(getContext(), "config", new String[]{"id", "token"});
        userInfo = ChatManager.Instance().getUserInfo(array[0], true);
        updateUserInfo(userInfo);
    }

    @OnClick({R2.id.fl_clear_cache, R2.id.rl_account_and_security, R2.id.rl_about_us, R2.id.rl_report_suggestion, R2.id.rl_version_cheack})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.fl_clear_cache) {// 缓存清理
            ShowClearPopWindow();
        } else if (id == R.id.rl_account_and_security) {
            Intent accountSecurity = new Intent(getActivity(), AccountSecurityActivity.class);
            getActivity().startActivity(accountSecurity);
        } else if (id == R.id.rl_about_us) {
            Intent aboutUS = new Intent(getActivity(), AboutUsActivity.class);
            getActivity().startActivity(aboutUS);
        } else if (id == R.id.rl_report_suggestion) {
            Intent reportSuggestion = new Intent(getActivity(), ReportSuggestionActivity.class);
            getActivity().startActivity(reportSuggestion);
        } else if (id == R.id.rl_version_cheack) {
            checkVersion();
        }
    }

    public void checkVersion() {
        new AndroidVersionUpdateRequest(getActivity(), new AndroidVersionUpdateRequest.OnAndroidVersionCheckListener() {
            @Override
            public void update(boolean updated, String url) {
                if (updated) {
                    ShowUpDatePopWindow(url);
                } else {
                    ShowUnUpDatePopWindow();
                }
            }
        });
    }


    PopupWindow popupWindow;
    private boolean isShowing;

    /**
     * 设置缓存大小显示
     */
    @SuppressLint("StaticFieldLeak")
    public void setClearCacheSize() {
        try {
            String userCachePath = Config.ROOT_CACHE_PATH + userViewModel.getUserId() + "/";
            new AsyncTask<String, Integer, String>() {
                @Override
                protected String doInBackground(String... params) {
                    String formatSize = null;
                    try {
                        long audioSize = DeletFileUtils.getFolderSize(new File(params[0]));
                        formatSize = DeletFileUtils.toFileSize((audioSize));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return formatSize;
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    if (tvCacheSize != null) {
                        tvCacheSize.setText((s));
                    }
                }
            }.execute(userCachePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Create by HEKE, 2019/10/14 15:26
     * TODO 显示清除确定窗口
     */
    private void ShowClearPopWindow() {
        TipDialog.showCustomDialogWithNewAttrs(getActivity(), R.string.wendy_title, R.string.newclear_cache_message, new int[]{R.string.newclear_all_datas,
                        R.string.newclear_only_pictures}, CustomAppUIDialog.TYPE_CONFIRM_CANCLE, true, 2, true, true,
                R.drawable.commom_white_gray, R.drawable.commom_white_gray, R.color.c646566, R.color.c646566, true, new TipDialog.OnMsgTipDialogListener() {
                    @Override
                    public void then(boolean confirm, boolean outtouch) {
                        if (confirm) {
                            TipDialog.showCustomDialog(getActivity(), R.string.wendy_title, R.string.newclear_all_tip_message, new int[]{R.string.confirm, R.string.cancle_but},
                                    CustomAppUIDialog.TYPE_CONFIRM_CANCLE, true, 2, true, new TipDialog.OnMsgTipDialogListener() {
                                        @Override
                                        public void then(boolean confirm, boolean outtouch) {
                                            if (confirm) {
                                                // 执行深度清除
                                                VariableFilesUtils.deleteDirectoryAsync(new String[]{Config.PHOTO_SAVE_DIR, Config.AUDIO_SAVE_DIR,
                                                        Config.VIDEO_SAVE_DIR, Config.FILE_SAVE_DIR}, new VariableFilesUtils.OnDeleteFilesListener() {
                                                    @Override
                                                    public void progress(int progress) {
                                                        Log.e("###### Delete Files ", progress + "% ");
                                                    }

                                                    @Override
                                                    public void result(boolean success, boolean error) {
                                                        if (success) {
                                                            ToastTip.tip(getString(R.string.newclear_success));
                                                            setClearCacheSize();
                                                        }
                                                    }
                                                });
                                            }
                                        }
                                    });
                        } else {
                            // 执行轻度清除，取消被点击
                            if (!outtouch) {
                                VariableFilesUtils.deleteDirectoryAsync(new String[]{Config.PHOTO_SAVE_DIR}, new VariableFilesUtils.OnDeleteFilesListener() {

                                    @Override
                                    public void progress(int progress) {
                                        Log.e("###### Delete Files ", progress + "% ");
                                    }

                                    @Override
                                    public void result(boolean success, boolean error) {
                                        if (success) {
                                            ToastTip.tip(getString(R.string.newclear_success));
                                            setClearCacheSize();
                                        }
                                    }
                                });
                            }
                        }
                    }
                });
    }

    private void ShowUpDatePopWindow(String url) {
        TipDialog.showCustomDialog(getActivity(), R.string.wendy_title, R.string.check_update_version, new int[]{R.string.confirm, R.string.cancle_but},
                CustomAppUIDialog.TYPE_CONFIRM_CANCLE, true, 2, true, new TipDialog.OnMsgTipDialogListener() {
                    @Override
                    public void then(boolean confirm, boolean outtouch) {
                        if (confirm) {
                            openBrowserThenDownload(getActivity(), url);
                        }
                    }
                });
    }

    private void ShowUnUpDatePopWindow() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.pop_no_version, null);
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);

        TextView tv_close = view.findViewById(R.id.tv_pop_close);
        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        setAlph(0.9f);
        if (!isShowing) {
            isShowing = true;
            popupWindow.showAtLocation(meLinearLayout, Gravity.CENTER, 0, 0);
        }
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlph(1f);
                isShowing = false;
                popupWindow = null;
            }
        });
    }

    /**
     * 调用第三方浏览器打开
     *
     * @param context
     * @param url     要浏览的资源地址
     */
    private void openBrowserThenDownload(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            getActivity().startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            Toast.makeText(getActivity(), "请下载浏览器", Toast.LENGTH_SHORT).show();
        }
    }

    private void setAlph(float f) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        //0.0-1.0
        lp.alpha = f;
        getActivity().getWindow().setAttributes(lp);
    }


}
